package org.objective.ddl.plugin.postgres;

import org.objective.ddl.type.DDLFieldInfo;
import org.objective.ddl.type.DataType;
import org.objective.service.DDLService;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 *
 * @author gus
 */
class DDLServiceImplement implements DDLService
{
    private final JdbcTemplate jdbcTemplate;

    DDLServiceImplement(JdbcTemplate jdbcTemplate)
    {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void createUserTable(String tableName, DDLFieldInfo[] fields) throws Exception
    {
        if (fields != null && fields.length != 0)
        {
            if (!isExistTable(tableName))
            {
                throw new Exception(String.format("table %s is exist", tableName));
            }

            StringBuilder builder = new StringBuilder(String.format("CREATE TABLE %s ", tableName));
            StringBuilder constraintsPK = new StringBuilder("PRIMARY KEY ( ");
            StringBuilder constraintsUK = new StringBuilder("UNIQUE KEY ( ");

            for (DDLFieldInfo field : fields)
            {
                String column = String.format("%s %s", field.getFieldName(), DataType.getDomain(field.getDataType()));
                builder.append(column);

                if (field.isPrimaryKey())
                {
                    constraintsPK.append(String.format("PK_%S_%S, ", tableName, field.getFieldName()));
                }

                if (field.isUnique())
                {
                    constraintsUK.append(String.format("UK_%S_%S, ", tableName, field.getFieldName()));
                }
            }

            constraintsPK.delete(constraintsPK.length()-2, -1).append(")");
            constraintsUK.delete(constraintsPK.length()-2, -1).append(")");
            
            if(constraintsPK.length() > 0)
                builder.append(", ").append(constraintsPK);
            if(constraintsUK.length() > 0)
                builder.append(", ").append(constraintsUK);

            jdbcTemplate.execute(builder.toString());

        }
    }

    @Override
    public boolean isExistTable(String tableName)
    {
        int result = jdbcTemplate.queryForInt("SELECT count(*) " +
            "FROM pg_tables  " +
            "where schemaname='public' and tablename=?", new Object[]
            {
                tableName
            });
        return result == 1;
    }

    @Override
    public void addColumn(String tableName, DDLFieldInfo column)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
